import 'package:easy_refresh/easy_refresh.dart';
import 'package:get/get.dart';
import 'package:wan_android_flutter/common/base/base_controller.dart';

import '../../../../../common/network/http_util.dart';
import '../../../../../common/network/json_parse.dart';
import '../../../../../common/network/model/knowledges_model.dart';
import '../../../../../common/network/model/single_knowledges_model.dart';
import 'single_knowledge_state.dart';

class SingleKnowledgeLogic extends BaseController {
  SingleKnowledgeLogic({required this.model});

  final SingleKnowledgeState state = SingleKnowledgeState();

  KnowledgeModel model;

  EasyRefreshController controller = EasyRefreshController(
    controlFinishRefresh: true,
    controlFinishLoad: true,
  );

  @override
  Future<void> onLoadData() async {
    super.onLoadData();
    loadSingleKnowledges();
  }

  Future<void> loadSingleKnowledges() async {
    final response = await httpUtil.get("/article/list/${state.pageIndex}/json?cid=${model.id}");
    if (response.statusCode == 200 && response.data is Map<String, dynamic>) {
      final singleKnowledgesModel = JsonParse.fromJsonMap<SingleKnowledgesModel>(response.data);
      if (singleKnowledgesModel?.data?.datas?.isNotEmpty == true) {
        if (state.pageIndex == 0) {
          state.singleKnowledgeList.assignAll(singleKnowledgesModel!.data!.datas!);
        } else {
          state.singleKnowledgeList.addAll(singleKnowledgesModel!.data!.datas!);
        }
        state.singleKnowledges.assignAll(state.singleKnowledgeList);
        controller.finishRefresh();
        controller.finishLoad();
      }
    }
  }
}
